/*
* TreeServiceImpl.java
* Created on  2014-6-8 下午7:49
* 版本       修改时间          作者      修改内容
* V1.0.1    2014-6-8       panzhuowen    初始版本
*
*/
package com.genghis.ptas.data.service.impl;

import com.genghis.ptas.data.dao.DataTableDao;
import com.genghis.ptas.data.service.TreeService;
import com.genghis.ptas.j48.J48algorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import weka.core.Instances;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类的描述信息
 *
 * @author panzhuowen
 * @version 1.0.1
 */
@Service("treeService")
public class TreeServiceImpl implements TreeService {
    @Autowired
    private DataTableDao dataTableDao;

    @Override
    public String getNeedString() {
        Instances instances = dataTableDao.getInstances();
        return new J48algorithm().getCfs(instances).toString().substring(36, new J48algorithm().getCfs(instances).toString().length() - 48);
    }

    @Override
    public List<Map<String, String>> getResultMap(String result) {
        List<String> root = new ArrayList<String>();
        List<String> child = new ArrayList<String>();
        List<Map<String, String>> treeList = new ArrayList<Map<String, String>>();
        String[] results = result.split("\n");
        int num = 0;
        for (int i = 0; i < results.length; i++) {
            if (results[i].startsWith("|")) {
                child.add(results[i]);
            } else {
                num++;

                if (num > 1) {
                    treeList.add(buildTree(root, child));
                    num = 1;
                    root.clear();
                    child.clear();
                }
                root.add(results[i]);
            }
        }
        treeList.add(buildTree(root, child));
        return treeList;
    }

    private Map<String, String> buildTree(List<String> root, List<String> child) {
        Map<String, String> map = new HashMap<String, String>();
        String tRoot = root.get(0);
        if (child.size() == 0) {
            map.put("null", tRoot);
        } else {
            for (String tChild : child) {
                map.put(tChild, tRoot);
            }
        }
        return map;
    }


}
